/**
 * 
 */
package vn.lumi.smarthome.network;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Time;
import vn.lumi.smarthome.ulti.Preference;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

/**
 * @author Chu Tuan Anh
 *
 */
public class UpdateScheduleInfo extends HCMsg {

	//variables
	private int newConfigVersion = 0;
	private int userId = 0;
	private int Schedule_id=0;
	private int ScheduleState = 0;
	private int Device_id = 0;
	private int Repeat, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
	private Time StartTime = new Time(); //[0] = hour, [1] =minute
	private Time EndTime = new Time();
//	private int Duration;
	private int[] DeviceState = null;
	
	private boolean isCorrectFormat = false;

	//byte positions
	private static final int userIdPos = 2;
	
	/**
	 * @param cmd_id: command id
	 * @param Msg_id: message id
	 */
	public UpdateScheduleInfo(int userId) {
		super(NetMessage.CMD_HC_UPDATE_SCHEDULE_INFO, 0);
		this.userId = userId;
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see vn.lumi.smarthome.network.HCMsg#parseMessage(byte[], int)
	 */
	@Override
	public void parseMessage(byte[] input, int length) {
		// TODO Auto-generated method stub
		isCorrectFormat = isCorrectFormat(input,length);
		if(isCorrectFormat == false) return;
		
		int currentPos = 0;
		this.Cmd_id = Byte2Unsigned(input[currentPos]);
		currentPos++;
		this.newConfigVersion = Byte2Unsigned(input[currentPos]);
		currentPos++;
		this.userId = Byte2Unsigned(input[currentPos]);
		currentPos++;
		this.Schedule_id = Byte2Unsigned(input[currentPos]);
		currentPos++;
		this.ScheduleState = Byte2Unsigned(input[currentPos]);
		currentPos++;
		this.Device_id = Byte2Unsigned(input[currentPos]);
		currentPos++;
		byte RepeatMode = input[currentPos];
		currentPos++;
		this.Repeat = getBitFromByte(RepeatMode, 7);
		this.Monday = getBitFromByte(RepeatMode, 6);
		this.Tuesday = getBitFromByte(RepeatMode, 5);
		this.Wednesday = getBitFromByte(RepeatMode, 4);
		this.Thursday = getBitFromByte(RepeatMode, 3);
		this.Friday = getBitFromByte(RepeatMode, 2);
		this.Saturday = getBitFromByte(RepeatMode, 1);
		this.Sunday = getBitFromByte(RepeatMode, 0);
		this.StartTime = new Time(Byte2Unsigned(input[currentPos]), Byte2Unsigned(input[currentPos+1]));
		currentPos+=2;
		this.EndTime = new Time(Byte2Unsigned(input[currentPos]), Byte2Unsigned(input[currentPos+1]));
		currentPos+=2;
		/*this.Duration = Byte2Unsigned(input[currentPos]);
		currentPos++;*/
		this.DeviceState = new int[]{Byte2Unsigned(input[currentPos])};
	}

	/* (non-Javadoc)
	 * @see vn.lumi.smarthome.network.HCMsg#doWhenReceived(android.content.Context)
	 */
	@Override
	public void doWhenReceived(Context context) {
		// TODO Auto-generated method stub
		if(isCorrectFormat == false) return;
		//find if schedule already exists
		String selection = new String(TBL_Schedule._ID+"=?");
		String[] selectionArgs = new String[]{this.Schedule_id+""};
//		Cursor cursor = context.getContentResolver().query(TBL_Scene.CONTENT_URI_SCENE, null, selection, selectionArgs, null);
		Cursor cursor = context.getContentResolver().query(TBL_Schedule.CONTENT_URI_SCHEDULE, null, selection, selectionArgs, null);
		boolean isNewSchedule = (cursor.getCount() == 0);
		int deviceStateId = 0; //device state id in db
		// A Tuan Anh
		/*if(isNewSchedule){
			cursor.moveToFirst();
			deviceStateId = cursor.getInt(cursor.getColumnIndex(TBL_Schedule.STATE_ID));
		}*/
		// Author : hieu
		if(!isNewSchedule){
			cursor.moveToFirst();
			deviceStateId = cursor.getInt(cursor.getColumnIndex(TBL_Schedule.STATE_ID));
		}
		// End sua	
		//save schedule into database
		
		if(isNewSchedule){
			//insert device state
			ContentValues contentValues=new ContentValues();
			contentValues.put(TBL_DeviceState.VALUE, this.DeviceState[0]);
			contentValues.put(TBL_DeviceState.BLIND_STATE, Device.DEVICE_STATE_BLIND_STATE_STOPPED);
			Uri uri2= context.getContentResolver().insert(TBL_DeviceState.CONTENT_URI_DEVICE_STATE, contentValues);
			deviceStateId=Integer.parseInt(uri2.getLastPathSegment());
			
			//insert schedule
			ContentValues values = new ContentValues();
			values.put(TBL_Schedule.STATE, this.ScheduleState);
			values.put(TBL_Schedule.DEVICE_ID, this.Device_id);
			values.put(TBL_Schedule.REPEAT, this.Repeat);
			values.put(TBL_Schedule.MONDAY, this.Monday);
			values.put(TBL_Schedule.TUESDAY, this.Tuesday);
			values.put(TBL_Schedule.WEDNESDAY, this.Wednesday);
			values.put(TBL_Schedule.THURSDAY, this.Thursday);
			values.put(TBL_Schedule.FRIDAY, this.Friday);
			values.put(TBL_Schedule.SATURDAY, this.Saturday);
			values.put(TBL_Schedule.SUNDAY, this.Sunday);
			values.put(TBL_Schedule.HOUR, this.StartTime.getHour());
			values.put(TBL_Schedule.MINUTE, this.StartTime.getMinute());
//			values.put(TBL_Schedule.DURATION, this.Duration);
			values.put(TBL_Schedule.HOUR_END, this.EndTime.getHour());
			values.put(TBL_Schedule.MINUTE_END, this.EndTime.getMinute());
			values.put(TBL_Schedule.STATE_ID, deviceStateId);
			context.getContentResolver().insert(TBL_Schedule.CONTENT_URI_SCHEDULE, values);
			
		}
		else{
			//update device state
			ContentValues contentValues=new ContentValues();
			contentValues.put(TBL_DeviceState.VALUE, this.DeviceState[0]);
			contentValues.put(TBL_DeviceState.BLIND_STATE, Device.DEVICE_STATE_BLIND_STATE_STOPPED);
			String selection1 = new String(TBL_DeviceState._ID+"=?");
			String[] selectionArgs1 = new String[]{deviceStateId+""};
			context.getContentResolver().update(TBL_DeviceState.CONTENT_URI_DEVICE_STATE, contentValues, selection1, selectionArgs1);
			
			//update schedule
			ContentValues values = new ContentValues();
			values.put(TBL_Schedule.STATE, this.ScheduleState);
			values.put(TBL_Schedule.DEVICE_ID, this.Device_id);
			values.put(TBL_Schedule.REPEAT, this.Repeat);
			values.put(TBL_Schedule.MONDAY, this.Monday);
			values.put(TBL_Schedule.TUESDAY, this.Tuesday);
			values.put(TBL_Schedule.WEDNESDAY, this.Wednesday);
			values.put(TBL_Schedule.THURSDAY, this.Thursday);
			values.put(TBL_Schedule.FRIDAY, this.Friday);
			values.put(TBL_Schedule.SATURDAY, this.Saturday);
			values.put(TBL_Schedule.SUNDAY, this.Sunday);
			values.put(TBL_Schedule.HOUR, this.StartTime.getHour());
			values.put(TBL_Schedule.MINUTE, this.StartTime.getMinute());
//			values.put(TBL_Schedule.DURATION, this.Duration);
			values.put(TBL_Schedule.HOUR_END, this.EndTime.getHour());
			values.put(TBL_Schedule.MINUTE_END, this.EndTime.getMinute());
			context.getContentResolver().update(TBL_Schedule.CONTENT_URI_SCHEDULE, values, selection, selectionArgs);
		}
			
		//save config in preferences
		LumiHome.HC_Config_ver = this.newConfigVersion;
		Preference.saveConfigVersion(context, this.newConfigVersion);
		
	}
	
	@Override
	public boolean isCorrectFormat(byte[] input, int length){
		boolean result = false;
		if(super.isCorrectFormat(input, length) == false)
			result =  false;
		else{
			if(this.userId == Byte2Unsigned(input[userIdPos])) result =  true;
			else result =  false;
		}
		return result;
	}

	public int getBitFromByte(byte in, int position)
	{
	   return (in >> position) & 1;
	}
}
